<?php
/**
 *
 *
 * @category     Shuxun Cms
 * @date         2015年10月25日
 * @author       Shuxun Team <kaiping.jiang@scshux.com>
 * @file         Auth.php
 */
namespace  Scshux\Plugin;
use Phalcon\Di;
use Scshux\Utils\Helper;
use Scshux\Mvc\SModel;
use Scshux\Utils\SiteConfig;
use Scshux\Mvc\SQuery;
use Scshux\Utils\Tree;
use Scshux\AbstractPlugin;
class  Auth extends AbstractPlugin
{

	private $_identity  = 0;
	private $_user      = null;
	private $_resources = null;

	/**
	 * Create api.
	 *
	 * @param DiInterface $di        Dependency injection.
	 * @param array       $arguments Api arguments.
	 */
	public function __construct()
	{
		$this->_identity = Di::getDefault()->get('session')->get('identity', 0);
	}


	/**
	 * 获取用户
	 */
	public  function  getUser()
	{
		if($this->_user == null){
			$userID = $this->getIdentity();
			if(empty($userID)) return null;
			$userDB = new SModel('admin_user');
			$this->_user = $userDB->getObj('user_id='.$userID);
		}
		return $this->_user;
	}


	/**
	 * 登录
	 */
	public  function  logLogin()
	{
		$data = array(
			'user_id'    => $this->getIdentity(),
			'info'       => '用户登录',
			'logindate'  => time(),
			'loginip'    => Helper::getIP(),
			'user_agent' => Helper::getUserAgent()
		);
		$loginLogDB = new SModel('admin_log');
		$loginLogDB->setData($data);
		$loginLogDB->add();

		$userDB = new SModel('admin_user');
		$userDB->setData(array(
			'logdip'  => Helper::getIP(),
			'logdate' => time()
		));
		$userDB->update('user_id='.$this->getIdentity());
	}


	/**
	 * Authenticate user.
	 *
	 * @param int $identity User identity.
	 *
	 * @return void
	 */
	public function authenticate($identity)
	{
		$this->_identity = $identity;
		Di::getDefault()->get('session')->set('identity', $identity);
	}

	/**
	 * Clear identity, logout.
	 *
	 * @return void
	 */
	public function clearAuth()
	{
		$this->_identity = 0;
		Di::getDefault()->get('session')->set('identity', 0);
	}


	/**
	 * Get current identity.
	 *
	 * @return int
	 */
	public function getIdentity()
	{
		return $this->_identity;
	}



}